let userListModule = (function(){
       // 获取元素
       let $deleteAll = $('.deleteAll'),
       $selectBox = $('.selectBox'),
       $searchInp = $('.searchInp'),
       $tableBox = $('.tableBox'),
       $tbody = $tableBox.find('tbody'),
       $checkList = null,
       $checkAll = $('#checkAll');
    //    $deleteAll = $('.deleteAll')
       // 绑定部门信息
         async function bindDepart(){
             let result = await queryDepart()
             if(result.code == 0){
                 let str = ``
                 result.data.forEach( item => {
                     str += `<option value="${item.id}">${item.name}</option>`
                 })
                 $selectBox.append(str)
             }
         }
         // 获取员工列表
         async function bindHtml(){
             let params = {
                 departmentId:$selectBox.val(),
                 search:$searchInp.val().trim()
             }
             let result = await axios.get('/user/list',{params})
             if(result.code !== 0)  return
             let str = ``
             result.data.forEach( item => {
                 let {id,name,sex,email,phone,department,job,desc} = item
                 str += `
                 <tr>
				<td class="w3"><input type="checkbox" userId="${id}"></td>
				<td class="w10">${name}</td>
				<td class="w5">${sex == 0?'男':'女'}</td>
				<td class="w10">${department}</td>
				<td class="w10">${job}</td>
				<td class="w15">${email}</td>
				<td class="w15">${phone}</td>
				<td class="w20">${desc}</td>
				<td class="w12"  userId="${id}">
					<a href="javascript:;">编辑</a>
					<a href="javascript:;">删除</a>
					<a href="javascript:;">重置密码</a>
				</td>
			</tr>`
             })
             $tbody.html(str)
             $checkList = $tbody.find('input[type="checkbox"]')
         }
         // 搜索触发数据重新绑定
         async function searchHandle(){
             $selectBox.change(bindHtml)
             $searchInp.on('keydown',ev=> {
                 if(ev.keyCode == 13){
                     bindHtml()
                 }
             })
         }
         // 基于事件委托实现
         function deletegate(){
             $tbody.click( async ev => {
                 let target = ev.target,
                 $target = $(target),
                 TAG = target.tagName,
                 TEXT = target.innerHTML.trim();
                 console.log(TEXT)
                 if(TAG === 'A'){
                     let userId = $target.parent().attr('userId')
                     if(TEXT === '编辑'){
                         console.log('编辑')
                            window.location.href=`userAdd.html?id=${userId}`
                            return
                     }
                     if(TEXT === '删除'){
                         console.log('删除')
                        let flag = confirm(`小主，您确定要删除编号为[${userId}]的信息吗，此操作不可撤销`)
                        if(!flag)  return
                        let result = await axios.get('/user/delete',{
                           params:{userId} 
                
                        })
                        if(result.code == 0){
                            alert('小主，已为您成功删除一条数据')
                            $target.parent().parent().remove()
                            $checkList = $tbody.find('input[type="checkbox"]')
                            return
                        }
                        alert('当前网络繁忙，请刷新后重试~~~')
                        return
                    }
                    if(TEXT === '重置密码'){
                        let flag = confirm(`小主，您确定要重置编号为[${userId}]的员工重置密码吗，此操作不可撤销`)
                        if(!flag)  return
                        let result = await axios.post('/user/resetpassword',{
                           userId
                 
                         })
                         if(result.code == 0){
                             alert('小主当前用户密码已被重置，赶快去通知用户把~~~')
                             return
                         }
                         alert('当前网络繁忙，请刷新后重试~~~')
                         return
                    }
                 }
                
             })
         }
         // 全选和非全选
          function selectHandle(){
              // 全选和非全选
              $checkAll.click(ev => {
                  let checked = $checkAll.prop('checked')
                  $checkList.prop('checked',checked)
              })
            $tbody.click(ev => {
                let target = ev.target
                TAG = target.tagName,
                $target = $(target)
                if(TAG = 'INPUT'){
                    let flag = true;
                    [].forEach.call($checkList,item => {
                      if(!$(item).prop("checked")){
                         flag = false
                      }
                    });
                    $checkAll.prop("checked",flag)
                }
            })
            // 删除
             $deleteAll.click(ev => {
                 // 获取当前选中项对应的员工编号
                 // 循环所有的checkbox，如果当前项是选中的
                 let arr = []
                 let transArray =  [].forEach.call($checkList) 
                 transArray.forEach($checkList,item => {
                    if($(item).prop("checked")){
                       arr.push($(item).attr("userId"))
                    }
                  });
                  // 如果没有选中要删除的项给与提示
                  if(arr.length === 0){
                      alert("小主，请先选中要删除的项~~~")
                      return 
                  }
                  // 删除前的确认提示
                  let flag = confirm(`小主，您确认要删除这${arr.length}条数据吗？`)
                  if(!flag) return
                  // 批量删除真实项目中有两种方案
                  // 把要删除的数据传给服务器，服务器自己删除,客户端不做处理
                  // 客户端自己基于递归删除
                  // 串行
                  let index = -1
                  let complete = () => {
                    if( index >= arr.length){
                        alert('小主，已为您删除选中的数据~~')
                    }else{
                        alert(`小主，已为您成功删除了${index+1}调数据，删除过程中部分数据无法删除，已为您停止`)
                    }
                    // 重新绑定数据
                    bindHtml()
                  }
                  let send =async  () => {
                      // 都删除
                      if(index >= arr.length) {
                          complete()
                          return
                      }
                    let userId = arr[++index]
                    let result = await axios.get('/user/delete',{
                        params:{
                            userId
                        }
                    })
                    if(result.code != 0)  {
                        complete()
                          return 
                    }  // 删除失败
                    send()
                  }
                  send()
             })
                
          }
    return{
        init(){
          bindDepart()
          bindHtml()
          deletegate()
          selectHandle()
        }
    }
})()
userListModule.init()